import os
import shutil
import zipfile
from pathlib import Path
from typing import List, Tuple
from ..config import EXTRACT_DIR, ALLOWED_EXTENSIONS, MAX_FILE_SIZE

def save_upload_file(file_content: bytes, filename: str) -> str:
    """保存上传的文件"""
    file_path = os.path.join(EXTRACT_DIR, filename)
    with open(file_path, 'wb') as f:
        f.write(file_content)
    return file_path

def extract_zip(zip_path: str) -> List[str]:
    """解压ZIP文件"""
    extracted_files = []
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(EXTRACT_DIR)
        for file in zip_ref.namelist():
            if file.lower().endswith('.pdf'):
                extracted_files.append(os.path.join(EXTRACT_DIR, file))
    return extracted_files

def get_file_info(file_path: str) -> Tuple[str, str, int]:
    """获取文件信息"""
    filename = os.path.basename(file_path)
    file_type = os.path.splitext(filename)[1].lower()[1:]
    file_size = os.path.getsize(file_path)
    return filename, file_type, file_size

def validate_file(file_type: str, file_size: int) -> bool:
    """验证文件类型和大小"""
    if file_type not in ALLOWED_EXTENSIONS:
        return False
    if file_size > MAX_FILE_SIZE:
        return False
    return True

def cleanup_temp_files(file_path: str):
    """清理临时文件"""
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
    except Exception as e:
        print(f"清理文件失败: {e}") 